package com.example.futureai.controller.login;

import com.example.futureai.constants.Result;
import com.example.futureai.mapper.user.UserMapper;
import com.example.futureai.po.User;
import com.example.futureai.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/chatLogin")
public class LoginController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    public Result checkLogin (@RequestBody User user){
        Result res = new Result();
        log.info("chickLogin入参{}",user.toString());
        //获取用户信息
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("username",user.getUsername());
        map.put("password",user.getPassword());
        List<User> usersList = userMapper.selectByMap(map);
        if(usersList.size() == 1){
            User userInfo = usersList.get(0);
            Map<String,String> tokenMap = new HashMap<>();
            tokenMap.put("username",userInfo.getUsername());
            tokenMap.put("password",userInfo.getPassword());
            String token = TokenUtil.getToken(tokenMap);
            return res.ok(token);
        }else{
            return res.fail("密码或账号错误！！");
        }
    }

    @RequestMapping("/register")
    public Result register (@RequestBody User user){
        Result res = new Result();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("phone",user.getPhone());
        List<User> users = userMapper.selectByMap(map);
        if(!CollectionUtils.isEmpty(users)){
            return res.fail("该手机号已注册！");
        }
        int num = userMapper.insert(user);
        if(num==1){
            return res.ok();
        }else{
            return res.fail("注册账户失败！");
        }
    }
}
